package org.hepeng.workx.spring.session.cookie;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.session.SessionAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.session.Session;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

/**
 * @author he peng
 */

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({Session.class , SessionAutoConfiguration.class})
public class CookieSerializerAutoConfiguration {

    public static class WritableCookieSerializerMarker {}

    @ConditionalOnBean(WritableCookieSerializerMarker.class)
    @Primary
    @Bean
    @ConditionalOnMissingBean
    public CookieSerializer writableCookieSerializer() {
        TopLevelDomainCookieSerializer cookieSerializer = new TopLevelDomainCookieSerializer();
        cookieSerializer.setCookiePath("/");
        cookieSerializer.setCookieMaxAge(-1);
        return cookieSerializer;
    }

    @Bean
    @ConditionalOnMissingBean
    public CookieSerializer readableCookieSerializer() {
        DefaultCookieSerializer cookieSerializer = new OnlyReadCookieSerializer();
        return cookieSerializer;
    }
}
